var debug = false;

$(function() {
	vDebug = getQueryString("debug");
	if (vDebug == 1)
		debug = true;
	else
		debug = false;
});

function log(text) {
	logTo(text, 'infoout');
}

function logTo(text, id) {
	var logdiv = $('#' + id);

	if (logdiv.length > 0) {
		logdiv.html(text);
	} else {
		console.log(text);
	}
}

function logappend(text) {
	var oldvar = $('#infoout').html();

	if (oldvar == undefined)
		log(text);
	else
		log(oldvar + text);
}

function toPage(url) {
	if (debug) {
		var index = url.indexOf('?');
		if (index >= 0) {
			url += "&debug=1"
		}
		else {
			url += "?debug=1"
		}
	}

	window.location.href = url;
}

function getQueryString(key) {
	return getQueryString(key, (false));
}

function getQueryString(key, def) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == key) {
			return pair[1];
		}
	}
	return def;
}

function returnConvert(txt) {
	var result = txt.replace(/\n/g, '<br>');
	result = result.replace(/\t/g, '&#9;');
	return result;
}

function setSelect(id, value) {
	var sel = $("#" + id);
	var item = sel.find("option[value=" + value + "]");
	item.attr("selected", true);
}

function cutWord(text, length) {
	if (text.length < length)
		return text;

	var result = text.substr(0, length);

	if (result.length > 5)
		result = result.substr(0, length - 3) + "...";
	return result;
}

function commonDownload(path, source, desc) {
	var done = false;

	var type = 0;
	var filename = "";

	jQuery.ajax({
		url: path,
		type: 'POST',
		data: source,
		contentType: 'application/json',
		secureuri: false,
		dataType: 'JSON',
		async: false,
		success: function(data) {

			if (checkApiErrorInfo(data, "请求文件失败")) {
				filename = data.fileName;
				type = data.type;
				done = true;
			}
		},
		error: function(e) {
			showAjaxError(e);
		}
	});

	if (done) {
		doDownload(type, filename);
	}
}

function doDownload(getEntity, type, fileName) {
	var url = urlRoot + "fileDownload/";
	var form = $("<form></form>").attr("action", url).attr("method", "post");
	form.append($("<input></input>").attr("type", "hidden").attr("name",
		"fileName").attr("value", fileName));
	form.append($("<input></input>").attr("type", "hidden")
		.attr("name", "type").attr("value", type));
	form.appendTo('body').submit().remove();
}

function doDataUpload(element, fullpath, callback) {
	var fileName = $('#' + element).val();

	if (fileName && fileName != '') {
		log("开始上传:" + fileName);
		$.ajaxFileUpload({
			url: fullpath,
			type: 'POST',
			data: '',
			secureuri: false,
			fileElementId: element,
			dataType: 'JSON',
			async: false,
			success: function(data) {
				var inner = JSON.parse($(data).html());

				if (checkApiErrorInfo(inner, "上传失败")) {
					log(fileName + "上传成功");
					if (callback) {
						callback(inner);
					}
				}
			},
			error: function(e) {
				console.log(e)
				showAjaxError(e);
			}
		});
	} else {
		log("警告-未选择任何文件！");
	}
}

function testCall(urlRoot, input, output) {
	jQuery.ajax({
		type: 'POST',
		contentType: 'application/json',
		url: urlRoot + 'test?input=' + input,
		dataType: 'json',
		async: false,
		success: function(data) {
			var res = data.result;
			output.html(res);
		},
		error: function(e) {
			showAjaxError(e);
		}
	});
}

function getAjaxError(jqXHR) {
	var responseText = jqXHR.responseXML;
	var error = responseText['error'];

	var msg = "服务器错误： [" + jqXHR.statusText + ": " + jqXHR.status + " " + error
		+ "] " + responseText['message'];
	return msg;
}

function showAjaxError(jqXHR) {
	showAjaxError(jqXHR, false);
}

function showAjaxError(jqXHR, parse) {
	if (parse) {
		var msg = getAjaxError(jqXHR);
		log(msg);
	} else
		log(jqXHR.responseText);
}

function checkApiCodeReturn(data, errorMsg, callback) {

	var code = data.code;
	if (code == 0)
		return true;

	var msg = data.message;
	if (errorMsg)
		msg = errorMsg + ": " + msg;

	var inner = data.data;
	if (inner) {
		var err = inner.errmsg;
		if (err)
			msg += '。' + err;
	}

	if (callback)
		callback(msg);
	else
		log(msg);

	return false;
}

function checkApiErrorInfo(data, errorMsg, callback, logToTarget) {

	var err = data["errmsg"];

	if (err == null || err == '0' || err == '') {
		return true;
	}

	if (callback) {
		callback(err);
	} else {
		var msg;

		if (errorMsg) {
			msg = errorMsg + ": ";
		}
		msg += err;

		if (logToTarget)
			logTo(msg, logToTarget);
		else
			log(msg);
	}

	return false;
}

function getNowDate() {
	var date = new Date();
	return "" + date.getFullYear() + "-" + (date.getMonth() + 1) + "-"
		+ date.getDate();
}

function getNowTime() {
	var date = new Date();

	return "" + date.getHours() + ":" + date.getMinutes() + ":"
		+ date.getSeconds();
}